package com.crm.system.controller.orderManager;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.crm.model.vo.orderManager.PtInvoiceBlueResultVO;
import com.vpiaotong.openapi.OpenApi;
import com.vpiaotong.openapi.util.Base64Util;
import com.vpiaotong.openapi.util.HttpUtils;
import com.vpiaotong.openapi.util.JsonUtil;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author:chaifuyou
 * @Date: 2021/7/26 14:24
 */
@RestController
@RequestMapping("/testInvoice")
@Slf4j
public class InvoiceTest {

    //私钥(与发给票通的公钥为一对)
    private static String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIVLAoolDaE7m5oMB1ZrILHkMXMF6qmC8I/FCejz4hwBcj59H3rbtcycBEmExOJTGwexFkNgRakhqM+3uP3VybWu1GBYNmqVzggWKKzThul9VPE3+OTMlxeG4H63RsCO1//J0MoUavXMMkL3txkZBO5EtTqek182eePOV8fC3ZxpAgMBAAECgYBp4Gg3BTGrZaa2mWFmspd41lK1E/kPBrRA7vltMfPj3P47RrYvp7/js/Xv0+d0AyFQXcjaYelTbCokPMJT1nJumb2A/Cqy3yGKX3Z6QibvByBlCKK29lZkw8WVRGFIzCIXhGKdqukXf8RyqfhInqHpZ9AoY2W60bbSP6EXj/rhNQJBAL76SmpQOrnCI8Xu75di0eXBN/bE9tKsf7AgMkpFRhaU8VLbvd27U9vRWqtu67RY3sOeRMh38JZBwAIS8tp5hgcCQQCyrOS6vfXIUxKoWyvGyMyhqoLsiAdnxBKHh8tMINo0ioCbU+jc2dgPDipL0ym5nhvg5fCXZC2rvkKUltLEqq4PAkAqBf9b932EpKCkjFgyUq9nRCYhaeP6JbUPN3Z5e1bZ3zpfBjV4ViE0zJOMB6NcEvYpy2jNR/8rwRoUGsFPq8//AkAklw18RJyJuqFugsUzPznQvad0IuNJV7jnsmJqo6ur6NUvef6NA7ugUalNv9+imINjChO8HRLRQfRGk6B0D/P3AkBt54UBMtFefOLXgUdilwLdCUSw4KpbuBPw+cyWlMjcXCkj4rHoeksekyBH1GrBJkLqDMRqtVQUubuFwSzBAtlc";

    //票通公钥(票通提供)
    private static String ptPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJkx3HelhEm/U7jOCor29oHsIjCMSTyKbX5rpoAY8KDIs9mmr5Y9r+jvNJH8pK3u5gNnvleT6rQgJQW1mk0zHuPO00vy62tSA53fkSjtM+n0oC1Fkm4DRFd5qJgoP7uFQHR5OEffMjy2qIuxChY4Au0kq+6RruEgIttb7wUxy8TwIDAQAB";

    //3DES秘钥(票通提供)
    private final static String password = "lsBnINDxtct8HZB7KCMyhWSJ";

    //请更换请求平台简称(票通提供)
    private  final static String platform_alias = "DEMO";

    //请更换请求平台编码(票通提供)
    private  final static String platform_code = "11111111";


    @PostMapping("/invoiceBlue")
    public String testInvoiceBlueOneItemAndPreferentialPolicy() {
        String url = "http://fpkj.testnw.vpiaotong.cn/tp/openapi/invoiceBlue.pt";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("taxpayerNum", "500102201007206608");  //销方税号
        map.put("invoiceReqSerialNo", date());//发票请求流水号
        map.put("buyerName", "购买方");//购买方名称
        map.put("buyerTaxpayerNum", "XX5001022010072066");//购买方税号(非必填,个人发票传null)
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Map<String, String> listMapOne = new HashMap<String, String>();
        listMapOne.put("taxClassificationCode", "1010101020000000000");//税收分类编码(可以按照Excel文档填写)
        listMapOne.put("quantity", "1.00");//数量
        listMapOne.put("goodsName", "货物名称");//货物名称
        listMapOne.put("unitPrice", "56.64");//单价
        listMapOne.put("invoiceAmount", "56.64");//金额
        listMapOne.put("taxRateValue", "0.16");//税率
        listMapOne.put("includeTaxFlag", "0");//含税标识
        //以下为零税率开票相关参数
        listMapOne.put("zeroTaxFlag", null);//零税率标识(空:非零税率,0:出口零税率,1:免税,2:不征税,3:普通零税率)
        listMapOne.put("preferentialPolicyFlag", null);//优惠政策标识(空:不使用,1:使用)   注:零税率标识传非空 此字段必须填写为"1"
        listMapOne.put("vatSpecialManage", null);//增值税特殊管理(preferentialPolicyFlag为1 此参数必填)
        list.add(listMapOne);
        map.put("itemList", list);
        String content = JsonUtil.toJson(map);
        System.out.println(content);
        //OpenApi参数内容(3des秘钥(票通提供),平台编码(票通提供),平台前缀(票通提供),私钥)
        String buildRequest = new OpenApi(password, platform_code, platform_alias, privateKey).buildRequest(content);
        System.out.println(buildRequest);
        String response = HttpUtils.postJson(url, buildRequest);
        System.out.println(response);
        Map<String, String> paramMap = JsonUtil.json2Map(response);
        log.info("结果  ------------");
        String contentStr = new OpenApi(password, platform_code, platform_alias, privateKey).disposeResponse(response, ptPublicKey);
        //JSONObject datas = JSONObject.parseObject(contentStr);
        PtInvoiceBlueResultVO resultVO = JSONObject.parseObject(contentStr, PtInvoiceBlueResultVO.class);
        log.info(resultVO.toString());
        return Base64Util.decode2String(resultVO.getContent().getQrCodePath());
    }

    public static void main(String [] s){
        String ss = "aHR0cDovL2Zwa2oudGVzdG53LnZwaWFvdG9uZy5jbi90cC9zY2FuLWludm9pY2Uvdmlldy8xdlEwc1pjVzlIR0NQUzg4TjRJd3BtczQ5SDBYWE8paC5wdA==";
        log.info(Base64Util.decode2String(ss));
    }

    public void testSign() {
        String content = "{\"taxpayerNum\":\"GAGA000000000001\",\"enterpriseName\":\"测试注册A\",\"platformCode\":\"13242753\",\"registrationCode\":\"87774618\",\"authorizationCode\":\"4209110715\"}";
        String buildRequest = new OpenApi("D5ImkGeVdsCaZyna4G73jv6j", "vZpDTUSV", "GAGA","") .buildRequest(content);

        System.out.println(buildRequest);
    }

    public static String doJsonPost(String url, String json,String authValue) {
        String result =null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler =new BasicResponseHandler();
        try {
            HttpPost httpPost =new HttpPost(url);
            StringEntity requestEntity =new StringEntity(json,"utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type","application/json");
            if(!ObjectUtil.isNull(authValue)){
                httpPost.setHeader("Authorization","Bearer "+authValue);
            }
            httpPost.setEntity(requestEntity);
            result = httpClient.execute(httpPost, responseHandler);
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }finally {
            try {
                httpClient.close();
            }catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        return result;
    }


    /**
     * 随机发票流水号生成
     */
    public  String date(){
        Date date = new Date();
        SimpleDateFormat sdf =new SimpleDateFormat("YYYYMMddHHmmss");
        String str=platform_alias+sdf.format(date)+(int)(Math.random()*90+10);
        System.out.println(str);
        return str;
    }

}
